package com.sannuo.manager.controller;

import com.sannuo.common.domain.UserLogin;
import com.sannuo.common.result.Result;
import com.sannuo.common.result.ResultCode;
import com.sannuo.common.utils.JWTUtils;
import com.sannuo.manager.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RequestMapping("/user")
@RestController
@Api(tags = "个人中心管理",description = "业务管理")
@CrossOrigin
public class LoginController {

    @Autowired
    private LoginService loginService;
    private static final Logger logger = LogManager.getLogger(LoginController.class);

    @RequestMapping(value = "doLogin",method = RequestMethod.POST)
    public Result loginfin(UserLogin userLogin){
        Map<String,Object> result = new HashMap<>();
        logger.info("用户名：[{}]", userLogin.getCustomerCode());
        logger.info("密码：[{}]", userLogin.getPassword());
        try {

            UserLogin userDB = loginService.login(userLogin);

            Map<String, String> map = new HashMap<>();
            map.put("id",userDB.getUserId().toString());
            map.put("name",userDB.getName());

            String token = JWTUtils.getToken(map);
            result.put("state", true);
            result.put("msg", "登录成功！！！");

            result.put("token", token);

            if(userDB.getStatus() == 1){
                return Result.ok(ResultCode.SUCCESS,userDB);
            }
            return Result.fail(ResultCode.FAIL,null);
        }catch (Exception e){
            return Result.fail(ResultCode.FAIL,null);
        }
    }

}
